import json
from pyecharts.charts import Line
from pyecharts.options import TitleOpts, ToolboxOpts, VisualMapOpts, LabelOpts

# 获取数据
f_us = open('E:/PythonBasicKnowledge/09 可视化（echarts）图表展示案例/折线图/数据/美国.txt', 'r', encoding='UTF-8')
data_us = f_us.read()
f_us.close()

f_jp = open('E:/PythonBasicKnowledge/09 可视化（echarts）图表展示案例/折线图/数据/日本.txt', 'r', encoding='UTF-8')
data_jp = f_jp.read()
f_jp.close()

f_in = open('E:/PythonBasicKnowledge/09 可视化（echarts）图表展示案例/折线图/数据/印度.txt', 'r', encoding='UTF-8')
data_in = f_in.read()
f_in.close()

# 去掉不符合JSON规范的字符串
data_us = data_us.replace('jsonp_1629344292311_69436(', '')  # 去掉开头
data_us = data_us[:-2]  # 去掉结尾的两个字符

data_jp = data_jp.replace('jsonp_1629350871167_29498(', '')  # 去掉开头
data_jp = data_jp[:-2]  # 去掉结尾的两个字符

data_in = data_in.replace('jsonp_1629350745930_63180(', '')  # 去掉开头
data_in = data_in[:-2]  # 去掉结尾的两个字符

# JSON字符串转换为字典
data_us = json.loads(data_us)
data_jp = json.loads(data_jp)
data_in = json.loads(data_in)

# 获取【键trend】对应的数据
trend_data_us = ((data_us['data'])[0])['trend']
trend_data_jp = ((data_jp['data'])[0])['trend']
trend_data_in = ((data_in['data'])[0])['trend']

# 获取日期数据，用于x轴。只需要2020年的数据👉切片结束下标是314
x_data_us = trend_data_us['updateDate'][:314]
x_data_jp = trend_data_jp['updateDate'][:314]
x_data_in = trend_data_in['updateDate'][:314]

# 获取确诊数据，用于y轴。只需要2020年的数据👉切片结束下标是314
y_data_us = trend_data_us['list'][0]['data'][:314]
y_data_jp = trend_data_jp['list'][0]['data'][:314]
y_data_in = trend_data_in['list'][0]['data'][:314]

# 生成折线图
line = Line()
# 设置x轴和y轴数据
line.add_xaxis(x_data_us)  # 三个国家的x轴数据都是一样的
line.add_yaxis('美国确诊人数', y_data_us, label_opts=LabelOpts(is_show=False))
line.add_yaxis('日本确诊人数', y_data_jp, label_opts=LabelOpts(is_show=False))
line.add_yaxis('印度确诊人数', y_data_in, label_opts=LabelOpts(is_show=False))
# 设置全局配置
line.set_global_opts(
    title_opts=TitleOpts(title='美国、日本和印度2020年确诊人数统计', pos_left='center', pos_bottom='1%'),
    toolbox_opts=ToolboxOpts(is_show=True),
    visualmap_opts=VisualMapOpts(is_show=True)
)
line.render()
